<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="./node_modules/axios/dist/axios.min.js"></script>
    <style>
      body {
        margin: 0;
        padding: 50px;
      }
      a {
        text-decoration: none;
      }
      table,
      th,
      td {
        margin-top: 20px;
        border: 1px solid black;
        /* 边框重合 */
        border-spacing: 0;
        border-collapse: collapse;
      }
      td,th{
        padding: 5px;
      }
    </style>
  </head>
  <body>
    <h1>用户列表</h1>
    <a href="./add.html">添加用户</a>
    <table>
      <thead>
        <th>id</th>
        <th>用户名</th>
        <th>密码</th>
        <th>操作</th>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td>张三</td>
          <td>1234</td>
          <td>
            <a href="">编辑</a>
            <a href="">删除</a>
          </td>
        </tr>
        <tr>
          <td>2</td>
          <td>李思</td>
          <td>1234</td>
          <td>
            <a href="">编辑</a>
            <a href="">删除</a>
          </td>
        </tr>
      </tbody>
    </table>
    <script>
      //获取tbody对象
      const tbody = document.querySelector('tbody')

      //发送axios
      axios.get('http://localhost:3000/users').then((res) => {
        console.log(res);

        //获取所有用户数组
        const arr = res.data

        //将用户数组中的js对象转成dom字符串,在拼接成一整个字符串,填充到tbody中
        tbody.innerHTML = arr.map(item => {
          console.log(item)
          return `<tr>
          <td>${item.id}</td>
          <td>${item.username}</td>
          <td>${item.password}</td>
          <td>
            <a href="./edit.html?id=${item.id}">编辑</a>
            <a href="" onclick='deleteItem(${item.id})' >删除</a>
          </td>
        </tr>`
        }).join('')
      });

      //实现删除的方法
      function deleteItem(id){
        //删除不走回收站,先确认一下,防止误删除
        const flag = confirm('你确定要删除吗?')

        if(flag){
          axios.delete(`http://localhost:3000/users/${id}`).then(res=>{
            location.href = './index.html'
          })
        }
      }
    </script>
  </body>
</html>
